<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入流程名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
            start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery" class="business resetBtn">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row>
        <el-row>
          <p class="pinformation">流程列表</p>
          <p class="totalStyle">共 {{ total }} 条数据</p>
        </el-row>
        <el-row style="padding-bottom: 5px; margin-left: 15px">
          <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" link icon="delete" @click="handleDelete" :disabled="multiple">删除</el-button>
        </el-row>
      </el-row>
      <el-table v-loading="loading" :data="definitionList" ref="mainTableRef" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="流程编号" align="center" prop="deploymentId" />
        <el-table-column label="流程标识" align="center" prop="flowKey" width="190" />
        <el-table-column label="流程分类" align="center" prop="categoryName" />
        <el-table-column label="流程名称" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-button class="el-dropdown-link" link @click="handleReadImage(scope.row.deploymentId)">
              <span>{{ scope.row.name }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="业务表单" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-button v-if="scope.row.formId" class="el-dropdown-link" link>
              <span>{{ scope.row.formName }}</span>
            </el-button>
            <label v-else>暂无表单</label>
          </template>
        </el-table-column>
        <el-table-column label="流程版本" align="center" width="80">
          <template #default="scope">
            <el-tag>v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.suspensionState === 1">激活</el-tag>
            <el-tag type="warning" v-if="scope.row.suspensionState === 2">挂起</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="部署时间" align="center" prop="deploymentTime" width="200" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-dropdown>
              <span class="el-dropdown-link"
                style="font-size: 14px !important; color: var(--theme-deep-color) !important">
                更多操作
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleLoadXml(scope.row)">
                    <el-icon>
                      <Edit style="color: green" />
                    </el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleConfig(scope.row)">
                    <el-icon>
                      <CopyDocument style="color: blue" />
                    </el-icon>
                    配置表单
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleFlowAuthority(scope.row)">
                    <el-icon>
                      <Link style="color: purple" />
                    </el-icon>
                    配置流程权限
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleFormAuthority(scope.row)">
                    <el-icon>
                      <Link style="color: purple" />
                    </el-icon>
                    配置表单权限
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleBusinessBtn(scope.row)">
                    <el-icon>
                      <Pointer style="color: var(--theme-deep-color)" />
                    </el-icon>
                    配置业务按钮
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.suspensionState === 1"
                    @click="handleUpdateSuspensionState(scope.row)">
                    <el-icon>
                      <CircleClose style="color: red" />
                    </el-icon>
                    挂起
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.suspensionState === 2"
                    @click="handleUpdateSuspensionState(scope.row)">
                    <el-icon>
                      <CircleCheck style="color: green" />
                    </el-icon>
                    激活
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(scope.row)">
                    <el-icon>
                      <Delete style="color: red" />
                    </el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />

      <!-- 用户导入对话框 -->
      <!-- <el-dialog :class="'el-dialog-theme3'"
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->

      <!-- 配置表单 -->
      <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
        v-model="open" title="配置表单" width="1300">
        <el-row :gutter="10">
          <el-col :span="12">
            <p class="pinformation">搜索条件</p>
            <el-row>
              <el-col :span="9">
                <el-form-item label="模板编号：" prop="tableCode">
                  <el-input v-model="configForm.tableCode" placeholder="请输入模板编号" clearable @keyup.enter="configs" />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="模板名称：" prop="tableName" label-width="80">
                  <el-input v-model="configForm.tableName" placeholder="请输入模板名称" clearable @keyup.enter="configs" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-row style="justify-content: center">
                  <el-button type="success" @click="configs">搜索</el-button>
                  <el-button class="business resetBtn" @click="resetConfigs">重置</el-button>
                </el-row>
              </el-col>
            </el-row>
            <p class="pinformation">模板列表</p>
            <el-table :data="configList" border height="60vh" v-loading="loading1" @select="handleSelect"
              @select-all="handleAllSelect">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="模板编号" align="center" prop="tableCode" />
              <el-table-column label="模板名称" align="center" prop="tableName" />
            </el-table>
            <pagination v-show="configTotal > 0" :total="configTotal" v-model:page="configForm.pageNum"
              v-model:limit="configForm.pageSize" @pagination="configs" />
          </el-col>
          <el-col :span="12">
            <p class="pinformation">已选模板列表</p>
            <el-table :data="selectionConfigList" border id="selectedTable" height="67.3vh" v-loading="loading2">
              <el-table-column label="序号" type="index" width="55" align="center" />
              <el-table-column label="模板编号" align="center" prop="tableCode" width="170" />
              <el-table-column label="模板名称" align="center" prop="tableName">
                <template #default="scope">
                  <span>{{ scope.row.tableName }}</span>
                  <span class="hideSpan1" v-show="false">{{
                    scope.row.tableId
                  }}</span>
                  <span class="hideSpan2" v-show="false">{{
                    scope.row.flowTitle
                  }}</span>
                  <span class="hideSpan3" v-show="false">{{
                    scope.row.flowTitleDisplay
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="流程标题" align="center" width="85">
                <template #default="scope">
                  <el-button link icon="Setting" @click="titleConfig(scope.row, scope.$index)" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80">
                <template #default="scope">
                  <el-button link icon="Delete" @click="delConfig(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="success" @click="save">确定</el-button>
            <el-button type="danger" @click="open = false">取消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 配置表单权限 -->
      <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
        v-model="authorityOpen" title="配置表单权限" width="1300">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane v-for="item in authorityList" :label="item.tableName" :name="item.tableId">
            <el-tabs v-model="authActName" class="demo-tabs" tabPosition="left" style="height: 65vh">
              <el-tab-pane v-for="corre in item.taskList" :label="corre.nodeName" :name="corre.nodeId"
                style="padding: 0 10px">
                <template v-if="authActName == corre.nodeId">
                  <el-row>
                    <p class="totalStyle">
                      共 {{ corre.authVoList.length }} 条数据
                    </p>
                    <el-row style="padding-bottom: 5px; margin-left: 15px">
                      <el-button link type="success" @click="handleEdit(corre.authVoList)">批量编辑</el-button>
                      <el-button link type="success" @click="handleReadonly(corre.authVoList)">批量只读</el-button>
                    </el-row>
                  </el-row>
                  <el-table :data="corre.authVoList" border height="60vh" @selection-change="handleSelectionChange1">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="任务名称" align="center">
                      <template #default="scope">
                        {{ corre.nodeName }}
                      </template>
                    </el-table-column>
                    <el-table-column label="控件名称" align="center" prop="componentName" :filters="corre.distinctComponent"
                      :filter-method="filterData" />
                    <el-table-column label="控件状态" align="center" prop="authId">
                      <template #default="scope">
                        <el-radio-group v-model="scope.row.authId" @change="authIdChange(scope.row)">
                          <el-radio :label="0">编辑</el-radio>
                          <el-radio :label="1">只读</el-radio>
                        </el-radio-group>
                        <el-checkbox label="必选" v-model="scope.row.isRequired" v-if="scope.row.authId == 0" />
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="success" @click="determine">确定</el-button>
            <el-button type="danger" @click="authorityOpen = false">取消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
        title="配置业务按钮" v-model="btnOpen" width="1300">
        <el-row>
          <el-row>
            <p class="pinformation">按钮列表</p>
            <p class="totalStyle">共{{ btnTotal }}条数据</p>
          </el-row>
          <el-row style="padding-bottom: 5px; margin-left: 15px">
            <el-button type="success" link icon="Plus" @click="handleBtnAdd">新增</el-button>
          </el-row>
        </el-row>

        <el-table class="business" v-loading="btnLoading" :data="btnList" height="50vh">
          <el-table-column label="序号" type="index" width="70" align="center" />
          <el-table-column label="按钮名称" align="center" prop="btnName" width="150" />
          <el-table-column label="按钮路径" align="center" prop="btnUrl" width="255" />
          <el-table-column label="按钮参数" align="center" prop="params" width="280" />
          <el-table-column label="描述" align="center" prop="btnRemark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
            <template #default="scope">
              <el-button link type="success" @click="editBtn(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="delBtn(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
        :title="btnTitle" v-model="addOrEditBtnOpen" v-if="addOrEditBtnOpen">
        <el-form :model="btnForm" ref="btnFormRef" label-width="80" :rules="rules">
          <el-form-item label="应用节点：" prop="btnName">
            <el-select v-model="btnForm.nodeIds" placeholder="" clearable filterable multiple style="width:100%">
              <el-option v-for="item in nodeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="按钮名称：" prop="btnName">
            <el-input v-model="btnForm.btnName" placeholder="请输入按钮名称" clearable />
          </el-form-item>
          <el-form-item label="按钮路径：" prop="btnUrl">
            <el-input v-model="btnForm.btnUrl" placeholder="请输入按钮路径" clearable />
          </el-form-item>
          <el-form-item label="按钮参数：" prop="params">
            <el-input type="textarea" placeholder :autosize="{ minRows: 3, maxRows: 7 }" v-model="btnForm.params"
              maxlength="500" show-word-limit />
          </el-form-item>
          <el-form-item style="margin-bottom: 5px !important">
            <div style="
                font-size: 12px;
                color: #169bd5;
                height: 15px;
                line-height: 15px;
              ">
              多个按钮参数以“、”间隔，默认值用“=”拼接列攻:
              contractId、customId=121
            </div>
          </el-form-item>
          <el-form-item label="描述：" prop="btnRemark">
            <el-input type="textarea" placeholder :autosize="{ minRows: 3, maxRows: 7 }" v-model="btnForm.btnRemark"
              maxlength="500" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="success" @click="btnSave">保存</el-button>
            <el-button type="danger" @click="addOrEditBtnOpen = false">取消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 流程图 -->
      <el-dialog :class="'el-dialog-theme3'" :draggable="true" :title="readImageTitle"
        v-model="readImageOpen" width="70%" append-to-body>
        <!-- <el-image :src="readImage.src"></el-image> -->
        <flow :xmlData="xmlData" />
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
        title="配置流程标题" v-model="titleOpen" v-if="titleOpen" @close="titleClose">
        <el-button link v-for="item in componentList" :key="item.componentId" :componentId="item.componentId"
          style="margin: 0 10px; color: var(--theme-deep-color) !important"
          @click="insert(item.componentName, item.componentId)" class="formula_but">{{ item.componentName }}</el-button>
        <div style="
            width: 100%;
            min-height: 10vh;
            border: 1px solid #dcdfe6;
            border-radius: 5px;
          " contentEditable="true" class="formula_assemble"></div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="success" @click="define">确定</el-button>
            <el-button type="danger" @click="titleOpen = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup name="Definition">
import {
  listDefinition,
  delDeployment,
  updateState,
  readXml,
  getConfigList,
  getSelectionConfigList,
  addDeployForm,
  getAuthorityForm,
  postAuthorityForm,
  btnFormSave,
  getbtnView,
  delBtnRow,
  getComList,
  getTitleForm,
  getNodeList
} from "@/api/flowable/definition";
import flow from "./task/flow.vue";
import { listBusBtnList } from "@/api/flowable/todo";
import Sortable from "sortablejs";

const route = useRoute();
const { proxy } = getCurrentInstance();

const open = ref(false);
const configList = ref([]);
const selectionConfigList = ref([]);

const authorityList = ref([]);
const authorityOpen = ref(false);
const activeName = ref("first");
const authActName = ref();

const dateRange = ref([]);
const definitionList = ref([]);
const total = ref(0);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const xmlData = ref();
const readImageTitle = ref("");
const readImageOpen = ref(false);
const router = useRouter();

const titleOpen = ref(false);
const componentList = ref([]);

const nodeList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    btnName: [{ required: true, message: "按钮名称不能为空", trigger: "blur" }],
    // params: [{ required: true, message: "按钮参数不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

function filterData(value, row, column) {
  const property = column["property"];
  return row[property] === value;
}
// 获取检测类型
function getList() {
  loading.value = true;
  listDefinition(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      definitionList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

watch(
  () => route.path,
  (newval, oldval) => {
    if (newval == "/flowable/definition" && oldval == "/index") {
      getList();
    }
  }
);

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 新增按钮操作
function handleAdd() {
  router.push({
    path: "/flowable/model",
    query: {},
  });
}
// 编辑按钮操作
function handleLoadXml(row) {
  router.push({
    path: "/flowable/model",
    query: {
      deployId: row.deploymentId,
    },
  });
}
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.deploymentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 删除按钮操作 */
function handleDelete(row) {
  const deploymentIds = row.deploymentId || ids.value;
  proxy.$modal
    .confirm("删除该流程也会删除关联的任务数据，确认要继续吗？")
    .then(function () {
      return delDeployment(deploymentIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
}

// 挂起/激活流程
function handleUpdateSuspensionState(row) {
  let state = 1;
  if (row.suspensionState === 1) {
    state = 2;
  }
  const params = {
    deployId: row.deploymentId,
    state: state,
  };
  updateState(params).then((res) => {
    proxy.$modal.msgSuccess(res.msg);
    getList();
  });
}
// 流程图查看
function handleReadImage(deploymentId) {
  // 发送请求，获取xml
  readXml(deploymentId).then((res) => {
    xmlData.value = res.data;
    readImageTitle.value = "流程图";
    readImageOpen.value = true;
  });
}

const loading1 = ref(false);
const loading2 = ref(false);
const configTotal = ref(0);
const configForm = ref({ pageSize: 10, pageNum: 1 });
const deploymentId = ref("");
const changeList = ref([]);

function handleConfig(row) {
  loading2.value = true;
  deploymentId.value = row.deploymentId;
  configs();
  getSelectionConfigList(row.deploymentId).then((res) => {
    selectionConfigList.value = []
    nextTick(() => {
      selectionConfigList.value = res.data;
      changeList.value = res.data;
      loading2.value = false;
      nextTick(() => {
        const div = document.getElementById("selectedTable");

        // 找到 div 中的 table 元素
        const table = div.getElementsByTagName("table")[1];

        // 找到 table 的 tbody 元素
        const tbody = table.querySelector("tbody");

        // 根据tbody 元素 增加 拖动sortable
        const sortable = new Sortable(tbody, {
          animation: 150,
          onEnd: function () {
            const rows = Array.from(tbody.children);
            changeList.value = rows.map((row, index) => {
              // 在这里可以根据需要获取每行的数据，并进行处理
              row.cells[0].innerText = index + 1;
              return {
                tableCode: row.cells[1].innerText,
                tableName: row.cells[2].innerText,
                tableId: row.cells[2].querySelector(".hideSpan1").innerText,
                flowTitle: row.cells[2].querySelector(".hideSpan2").innerText,
                flowTitleDisplay:
                  row.cells[2].querySelector(".hideSpan3").innerText,
              };
            });
          },
        });
      });
    })
  });
  open.value = true;
}

function configs() {
  loading1.value = true;
  getConfigList(configForm.value).then((res) => {
    configList.value = res.rows;
    configTotal.value = res.total;
    loading1.value = false;
  });
}

function resetConfigs() {
  configForm.value = { pageNum: 1, pageSize: 10 };
  configs();
}

function handleSelect(selection, row) {
  if (!selectionConfigList.value.some((item) => item.tableId === row.tableId)) {
    selectionConfigList.value = [];
    nextTick(() => {
      changeList.value.push(row);
      selectionConfigList.value = JSON.parse(JSON.stringify(changeList.value));
    });
  }
}

function handleAllSelect(selection) {
  // if (selection.length>0) {
  const combinedArray = changeList.value.concat(configList.value);
  const uniqueArray = combinedArray.reduce((acc, obj) => {
    const found = acc.find((item) => item.tableId === obj.tableId);
    if (!found) {
      acc.push(obj);
    }
    return acc;
  }, []);
  selectionConfigList.value = []
  nextTick(() => {
    selectionConfigList.value = uniqueArray;
    changeList.value = uniqueArray
  })
  // }
}

function save() {
  selectionConfigList.value = []
  nextTick(() => {
    selectionConfigList.value = JSON.parse(JSON.stringify(changeList.value));
    if (selectionConfigList.value.length === 0) {
      proxy.$modal.msgError("至少选择一条！");
      return false;
    }
    addDeployForm({
      deployId: deploymentId.value,
      flowDeployFormList: selectionConfigList.value,
    }).then((res) => {
      open.value = false;
      proxy.$modal.msgSuccess("保存成功");
      getList();
      configForm.value = { pageSize: 10, pageNum: 1 };
    });
  })
}
function handleFlowAuthority(row){
  
}
function handleFormAuthority(row) {
  authorityOpen.value = true;
  getAuthorityForm(row.id, row.deploymentId).then((res) => {
    authorityList.value = res.data;
    authorityList.value.forEach((item) => {
      item.taskList.forEach((item1) => {
        let map = new Map();
        item1.distinctComponent = [];
        item1.authVoList.forEach((row) => {
          if (row.required === 0) {
            row.isRequired = false;
          } else if (row.required === 1) {
            row.isRequired = true;
          }
          // componentId
          if (!map.has(row["componentId"])) {
            map.set(row["componentId"]);
            item1.distinctComponent.push({
              value: row["componentName"],
              text: row["componentName"],
            });
          }
        });
      });
    });
    activeName.value = res.data[0]?.tableId;
    authActName.value = res.data[0]?.taskList[0]?.nodeId;
  });
}

function delConfig(scope) {
  selectionConfigList.value.splice(scope.$index, 1);
  changeList.value = selectionConfigList.value;
}

function determine() {
  //重新赋值防止因删除下面的代码：delete row.isRequired而引起页面的抖动，影响体验。
  let tableAuthList = JSON.parse(JSON.stringify(authorityList.value));
  // console.log(tableAuthList)
  tableAuthList.forEach((item) => {
    item.taskList.forEach((item1) => {
      delete item.distinctComponent;
      item1.authVoList.forEach((row) => {
        if (row.authId === 0) {
          if (row.isRequired === true) {
            row.required = 1;
          } else if (row.isRequired === false) {
            row.required = 0;
          }
          //必须删掉，后端bean不允许不存在的属性传入。
          delete row.isRequired;
        } else {
          delete row.required;
          delete row.isRequired;
        }
      });
    });
  });

  postAuthorityForm(tableAuthList).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    authorityOpen.value = false;
  });
}

const selectionList = ref([]);

function handleSelectionChange1(selection) {
  selectionList.value = selection;
}

function handleEdit(list) {
  for (let item2 of selectionList.value) {
    for (let item1 of list) {
      if (item1.id === item2.id) {
        item1.authId = 0;
      }
    }
  }
}

function handleReadonly(list) {
  for (let item2 of selectionList.value) {
    for (let item1 of list) {
      if (item1.id === item2.id) {
        item1.authId = 1;
      }
    }
  }
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

function authIdChange(row) {
  if (row.authId) {
    delete row.isRequired;
  } else {
    row.isRequired = false;
  }
}

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

getList();

const btnOpen = ref(false);
const btnList = ref([]);
const btnLoading = ref(false);
const btnTotal = ref(0);
const btnTitle = ref("");
const addOrEditBtnOpen = ref(false);
const btnForm = ref({});
const deployId = ref("");

// 配置业务按钮
function handleBusinessBtn(row) {
  btnOpen.value = true;
  btnList.value = [];
  btnTotal.value = 0;
  deployId.value = row.deploymentId;
  getNodeList(row.id).then(res => {
    nodeList.value = res.data
  })
  obtainBtnList();
}

function obtainBtnList() {
  btnLoading.value = true;
  if(!deployId.value){
    btnList.value = [];
    return;
  }
  listBusBtnList({ deployId: deployId.value }).then((res) => {
    btnList.value = res.data;
    btnTotal.value = res.data.length;
    btnLoading.value = false;
  });
}

function handleBtnAdd() {
  btnTitle.value = "新增按钮";
  addOrEditBtnOpen.value = true;
  btnForm.value = {};
}

function btnSave() {
  proxy.$refs["btnFormRef"].validate((valid) => {
    if (valid) {
      btnForm.value.deployId = deployId.value;
      btnFormSave(btnForm.value).then((res) => {
        proxy.$modal.msgSuccess("保存成功");
        addOrEditBtnOpen.value = false;
        obtainBtnList();
      });
    }
  });
}

function editBtn(row) {
  btnTitle.value = "编辑按钮";
  addOrEditBtnOpen.value = true;
  btnForm.value = {};
  getbtnView(row.btnId).then((res) => {
    btnForm.value = res.data;
  });
}

function delBtn(row) {
  proxy.$modal
    .confirm("确定删除该按钮吗？")
    .then(function () {
      return delBtnRow(row.btnId);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
      obtainBtnList();
    });
}

function getRange() {
  const selection = window.getSelection();
  if (selection.getRangeAt && selection.rangeCount > 0) {
    return { range: selection.getRangeAt(0), selection };
  }

  const range = document.createRange();
  range.setStart(selection.anchorNode, selection.anchorOffset);
  range.setEnd(selection.focusNode, selection.focusOffset);
  return { range, selection };
}

function getSpan(className, text, id) {
  if (id) {
    const span = document.createElement("span");
    span.className = className;
    span.innerText = text;
    span.setAttribute("contenteditable", "false");
    span.setAttribute("componentId", id);
    return span;
  } else {
    return document.createTextNode(text);
  }
}

function insert(num, id) {
  const { range } = getRange();
  const span = getSpan("to_show_span", num, id);

  const formulaAssemble = document.querySelector(".formula_assemble");
  if (
    range.commonAncestorContainer === formulaAssemble ||
    (range.commonAncestorContainer.nodeType === Node.TEXT_NODE &&
      range.commonAncestorContainer.parentNode === formulaAssemble)
  ) {
    range.insertNode(span);
  } else {
    let lastChild = formulaAssemble.lastElementChild;
    if (!lastChild) {
      lastChild = formulaAssemble.lastChild;
    }
    if (lastChild && lastChild.nodeType === Node.TEXT_NODE) {
      formulaAssemble.insertBefore(span, lastChild.nextSibling);
    } else {
      formulaAssemble.appendChild(span);
    }
  }

  const newRange = document.createRange();
  newRange.setStartAfter(span);
  newRange.setEndAfter(span);

  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(newRange);

  formulaAssemble.focus();
}

const settingIndex = ref(0);
function titleConfig(row, index) {
  titleOpen.value = true;
  settingIndex.value = index;
  getComList(row.tableId).then((res) => {
    componentList.value = res.data;
  });
  // getTitleForm(row.tableId, deploymentId.value).then((res) => {
  titleForm.value = row;
  titleForm.value.tableId = row.tableId;
  titleForm.value.deployId = deploymentId.value;
  nextTick(() => {
    if (titleForm.value.flowTitle) {
      const divElement = document.querySelector(".formula_assemble");
      if (titleForm.value.flowTitle.charAt(0) === "φ") {
        titleForm.value.flowTitle = titleForm.value.flowTitle.slice(1);
      }
      let expressList = titleForm.value.flowTitle.split("φ");
      expressList.forEach((item) => {
        let isComponent = item.split("Ψ");
        if (isComponent.length > 1) {
          let spanElement = document.createElement("span");
          spanElement.setAttribute("componentId", isComponent[0]);
          spanElement.setAttribute("contenteditable", "false");
          spanElement.textContent = isComponent[1];
          spanElement.className = "to_show_span";
          divElement.appendChild(spanElement);
        } else {
          let textNode = document.createTextNode(item);
          divElement.appendChild(textNode);
        }
      });
    }
  });
  // });
}

const titleForm = ref({});

function define() {
  const divElement = document.querySelector(".formula_assemble");
  if (!divElement.hasChildNodes()) {
    proxy.$modal.msgError("请输入配置流程标题！");
    return;
  }
  titleForm.value.flowTitleDisplay = "";
  titleForm.value.flowTitle = "";
  divElement.childNodes.forEach((node) => {
    if (node.nodeType === Node.ELEMENT_NODE) {
      titleForm.value.flowTitleDisplay += node.textContent;
    } else if (node.nodeType === Node.TEXT_NODE) {
      titleForm.value.flowTitleDisplay += node.nodeValue;
    }
  });

  const childNodes = divElement.childNodes;
  Array.from(childNodes).forEach((node) => {
    if (node instanceof HTMLSpanElement) {
      const componentId = node.getAttribute("componentId");
      if (componentId) {
        titleForm.value.flowTitle +=
          "φ" +
          componentId +
          "Ψ" +
          proxy.getItemByArray(
            componentList.value,
            "componentId",
            componentId,
            "componentName"
          ) +
          "φ";
      } else {
        titleForm.value.flowTitle += node.innerText;
      }
    } else {
      titleForm.value.flowTitle += node.textContent;
    }
  });

  selectionConfigList.value[settingIndex.value] = Object.assign(
    selectionConfigList.value[settingIndex.value],
    titleForm.value
  );
  titleOpen.value = false;
}

function titleClose() {
  titleForm.value = {};
  let divElement = document.querySelector(".formula_assemble");
  if (divElement) {
    divElement.innerText = "";
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-dropdown) {
  height: 23px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.mutipleFormsClass {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid;
  border-radius: 15px;
}

:deep(.to_show_span) {
  background-color: skyBlue !important;
  color: #fff !important;
  margin: 0 5px;
  border-radius: 5px;
  padding: 3px 10px;
  height: 20px;
}

:deep(.el-tabs__nav.is-left) {
  margin-top: 23vh;
}
</style>
